const sendMessage = require('../home/home.js')
Page
({
  data: 
  {
    info:"",                //显示框
    devices:"",             //所有搜索到的蓝牙设备
    connectedDeviceId:"",   //连接上的设备的ID
    services: "" ,          //连接上设备的所有服务
    dataList:[],//数据列表
  },
  onShow:function () {
    var that = this;
    that.closeBluetoothAdapter();//初始化蓝牙
  },
  //关闭蓝牙模块、释放蓝牙资源，保证连接顺畅
  closeBluetoothAdapter(){ 
    var that = this
    wx.closeBluetoothAdapter({
      complete(){
        that.BLEInit();//初始化蓝牙
      }
    })
  },
  /****************1.蓝牙初始化***************/
  BLEInit(event)
  {
      var that = this;
      wx.openBluetoothAdapter
      ({
          success: function (res) 
          {
          //  console.log("初始化蓝牙适配器成功");
            that.BLEState();//获取蓝牙状态
          },
          fail: function (res) 
          {
            //util.getSetting(2);
            wx.showModal({
              title: '提示',
              content: '请打开蓝牙和定位功能',
              confirmText: "确认",
              cancelText: "取消",
              success: function(res) {
                  //点击“确认”时打开设置页面
                  if (res.confirm) {
                      console.log('用户点击确认')
                      //wx.openSetting({})
                  } else {
                      console.log('用户点击取消')
                  }
              }
            })
          }
      })
  },
  /****************2.获取蓝牙状态***************/
  BLEState(event)
  {
    var that = this;
    wx.getBluetoothAdapterState
    ({
        success: function (res) 
        {
          //打印相关信息
           //console.log(JSON.stringify(res.errMsg) + "\n蓝牙是否可用：" + res.available);
           that.BLESearch();//搜索设备
        },
        fail: function (res) 
        {
          wx.showModal({
            title: '提示',
            content: '蓝牙不可用',
            confirmColor: '#00b6b5',
            showCancel: false,
          })
        }
    })
 
  },
  /****************3.搜索设备**************/
  BLESearch(event)
  {
    var that = this;
    wx.startBluetoothDevicesDiscovery
    ({
        services: [], //如果填写了此UUID，那么只会搜索出含有这个UUID的设备，建议一开始先不填写
        success: function (res) 
        {
         // console.log('搜索设备返回' + JSON.stringify(res))
          that.onBluetoothDeviceFound();//监听搜索的新设备事件
        }
    })
  },
  /****************4.监听搜索的新设备事件***************/
  onBluetoothDeviceFound() {
    //监听搜索到新设备的事件
    wx.onBluetoothDeviceFound((res) => {
      var that = this;
     // console.log(res)
      res.devices.forEach(device => {
        if(device.name.indexOf("DM") == -1){
           return;
        }
        if (!device.name && !device.localName) {
          return
        }
         console.log("localName："+device.localName+"name："+device.name+" deviceId："+device.deviceId)
        const foundDevices = that.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
      
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        that.setData(data);
      })
    })
  },
 
  connect (e){
    wx.showLoading({
      title: '加载中',
    });
     sendMessage.BLEConnect(e);
     setTimeout(()=>{
      wx.navigateBack({
        delta: 1
      });
     },1000)
     setTimeout(()=>{
      wx.hideLoading();
    },20000)
  },
});


function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

